package cn.innosmart.aq.view.fragment;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.InputFilter;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkError;
import com.android.volley.NoConnectionError;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.daimajia.androidanimations.library.Techniques;
import com.daimajia.androidanimations.library.YoYo;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import cn.innosmart.aq.R;
import cn.innosmart.aq.adapter.EmployeeAdapter;
import cn.innosmart.aq.application.AQApplication;
import cn.innosmart.aq.bean.Employee;
import cn.innosmart.aq.customize.InputDialog;
import cn.innosmart.aq.util.FragmentManagerTool;
import cn.innosmart.aq.util.INetworkInteractUtil;
import cn.innosmart.aq.util.NetworkInteractUtil;
import cn.innosmart.aq.util.SharedUtil;
import cn.innosmart.aq.util.SystemConstant;

public class AssignEmployeeFragment extends BaseFragment implements INetworkInteractUtil {
    InputDialog inputUidDialog;
    private NetworkInteractUtil networkInteractUtil;
    private ListView lvEmployee;
    private TextView tvEmpty;
    private Toolbar toolbar;
    private View.OnClickListener onNavigationClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            getActivity().onBackPressed();
        }
    };

    private Menu menus;
    private boolean isModify;
    private EmployeeAdapter employeeAdapter;
    private Toolbar.OnMenuItemClickListener onMenuItemClick = new Toolbar.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem menuItem) {
            switch (menuItem.getItemId()) {
                case R.id.action_add:
                    showInputDialog();
                    break;
                case R.id.action_edit:
                    isModify = !isModify;
                    employeeAdapter.startModify(isModify);
                    if (isModify) {
                        menus.findItem(R.id.action_add).setVisible(false);
                        menus.findItem(R.id.action_edit).setTitle(R.string.action_exit_edit);
                    } else {
                        menus.findItem(R.id.action_add).setVisible(true);
                        menus.findItem(R.id.action_edit).setTitle(R.string.edit);
                    }
                    break;
            }
            return true;
        }
    };
    private ArrayList<Employee> employees;
    private Employee preRemoveEmployee;
    private View.OnClickListener onDeleteClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Employee employee = (Employee) v.getTag();
            JSONObject jsonParams = new JSONObject();
            try {
                jsonParams.put("assignTo", employee.username);
                jsonParams.put("did", SystemConstant.currentBoxBean.getHubId());
            } catch (JSONException e) {
                e.printStackTrace();
            }
            preRemoveEmployee = employee;
            showLoadingDialog(getActivity());
            networkInteractUtil.removeEmployee(jsonParams);
        }
    };
    private AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Employee employee = employees.get(position);
            AssignedBoxFragment assignedBoxFragment = new AssignedBoxFragment();
            assignedBoxFragment.setEmployee(employee);
            FragmentManagerTool.addToBackStackFragment(getActivity().getSupportFragmentManager(), assignedBoxFragment, R.id.boxdetail_content);
//            FragmentManagerTool.replaceFragment(getActivity().getSupportFragmentManager(), new AssignedBoxFragment(), R.id.boxdetail_content);
        }
    };

    private void showInputDialog() {
        if (inputUidDialog == null) {
            inputUidDialog = new InputDialog(getActivity());
            inputUidDialog.setHint(getActivity().getString(R.string.employee_count));
            inputUidDialog.setTitle(getActivity().getString(R.string.add_employeee));
            final EditText etUserCount = (EditText) inputUidDialog.findViewById(R.id.et_name);
            InputFilter[] filters = {new InputFilter.LengthFilter(15)};
            etUserCount.setFilters(filters);
            inputUidDialog.setPositiveButton(getActivity().getString(R.string.sure), new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    final String userCount = etUserCount.getText().toString().trim();
                    if (TextUtils.isEmpty(userCount)) {
                        showToast(getActivity().getString(R.string.count_can_not_empty));
                        return;
                    }

                    JSONObject userCountJSon = new JSONObject();
                    try {
                        userCountJSon.put("assignTo", userCount);
                        userCountJSon.put("did", SystemConstant.currentBoxBean.getHubId());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    showLoadingDialog(getActivity());
                    networkInteractUtil.addEmployee(userCountJSon);
                }
            });
            inputUidDialog.setNegativeButton(getActivity().getString(R.string.cancel), new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    inputUidDialog.dismiss();
                }
            });
        } else {
            EditText etUserCount = (EditText) inputUidDialog.findViewById(R.id.et_name);
            etUserCount.setText("");
        }
        inputUidDialog.show();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        setHasOptionsMenu(true);
        return inflater.inflate(R.layout.fragment_assign_employee, null);
    }

    private void setBar() {
        toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
//        toolbar.setNavigationIcon(R.drawable.toolbar_back);
        ((ImageView) getActivity().findViewById(R.id.iv_headicon)).setImageResource(R.drawable.toolbar_back);
        toolbar.setTitle("");
        ((TextView) getActivity().findViewById(R.id.tv_toolbar)).setText(getString(R.string.employee_list));
//        toolbar.setTitle(getString(R.string.employee_list));
        ((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
//        toolbar.setNavigationOnClickListener(onNavigationClickListener);
        getActivity().findViewById(R.id.iv_headicon).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().onBackPressed();
            }
        });
        toolbar.setOnMenuItemClickListener(onMenuItemClick);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        setBar();
        getData();
        lvEmployee = (ListView) view.findViewById(R.id.lv_employee);

        tvEmpty = (TextView) view.findViewById(R.id.tv_empty);
        lvEmployee.setEmptyView(tvEmpty);
//        lvEmployee.setOnItemClickListener(onItemClickListener);
        networkInteractUtil = new NetworkInteractUtil(this);
    }

    public void onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        getActivity().getMenuInflater().inflate(R.menu.menu_assign, menu);
        menus = menu;
        super.onCreateOptionsMenu(menu, inflater);
    }

    private void getData() {
        JSONObject jsonParam = new JSONObject();

        try {
            jsonParam.put("userid", SharedUtil.getInstance().readUserId());
//            jsonParam.put("did", "577ca942b78f559615223e26");
            jsonParam.put("did", SystemConstant.currentBoxBean.getHubId());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        JsonObjectRequest refreshAssigneeRequest = new JsonObjectRequest(Request.Method.POST, SystemConstant.getUserAssignUrl, jsonParam,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        System.out.println("result=" + response);
                        int resultCode = -1;
                        try {
                            resultCode = response.getInt("code");
                            if (resultCode == 0) {
                                employees = new ArrayList<>();
                                try {
                                    for (int i = 0; i < response.getJSONArray("assignTo").length(); i++) {
                                        Employee employee = new Employee();
                                        JSONObject jsonObject = response.getJSONArray("assignTo").getJSONObject(i);
                                        employee.username = jsonObject.getString("username");
                                        employee.nickName = jsonObject.getString("nickname");
                                        employees.add(employee);
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                SystemConstant.employees = employees;
                            } else {
                                employees = new ArrayList<>();
                            }

                            employeeAdapter = new EmployeeAdapter(getActivity(), employees);
                            employeeAdapter.setOnDeleteClickListener(onDeleteClickListener);
                            lvEmployee.setAdapter(employeeAdapter);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> header = new HashMap<String, String>();
                header.put("Authorization", " Bearer " + SystemConstant.session_token);
                return header;
            }

            ;
        };
        AQApplication.getInstance().mQueue.add(refreshAssigneeRequest);


//        if (SystemConstant.employees == null) {
//            if (employees == null)
//                employees = new ArrayList<>();
//            JSONObject jsonLoginInfo = SharedUtil.getInstance().readUserInfo();
//            try {
//                JSONArray jsonEmpoyees = jsonLoginInfo.getJSONArray("employee");
//                Employee employee;
//                for (int i = 0; i < jsonEmpoyees.length(); i++) {
//                    JSONObject jsonObject = jsonEmpoyees.getJSONObject(i);
//                    employee = JSON.parseObject(jsonObject.toString(), Employee.class);
//                    employees.add(employee);
//                }
//            } catch (JSONException e) {
//                e.printStackTrace();
//            }
//            SystemConstant.employees = employees;
//        } else {
//            employees = SystemConstant.employees;
//        }

    }

    @Override
    public void onNetworkInteractAllOver(int ret) {

    }

    @Override
    public void onNetworkInteractOver(int ret, String flag, Object object) {
        hideLoadingDialog();
        if (flag.equals(networkInteractUtil.ADDEMPLOYEE)) {
            switch (ret) {
                case 0:
                    JSONObject jsonResponse = (JSONObject) object;
                    JSONObject jsonUserInfo = null;
                    try {
                        jsonUserInfo = jsonResponse.getJSONObject("userinfo");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    Employee employee = new Employee();
                    try {
                        employee.nickName = jsonUserInfo.getString("nickname");
                        employee.username = jsonUserInfo.getString("username");
                        employee.id = jsonUserInfo.getString("id");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    employees.add(employee);
                    employeeAdapter.refresh(employees);
                    showToast(getActivity().getString(R.string.add_success));
                    inputUidDialog.dismiss();
                    break;
                case 1:
                    YoYo.with(Techniques.Shake).playOn(inputUidDialog.findViewById(R.id.et_name));
                    showToast(getActivity().getString(R.string.count_is_not_exist));
                    break;
                case 3:
                    YoYo.with(Techniques.Shake).playOn(inputUidDialog.findViewById(R.id.et_name));
                    showToast(getActivity().getString(R.string.count_had_been_added));
                    break;
                case 2:
                default:
                    showToast(getActivity().getString(R.string.add_failed));
                    break;
            }
        } else if (flag.equals(networkInteractUtil.REMOVEEMPLOYEE)) {
            System.out.println("object=" + object.toString());
            switch (ret) {
                case 0:
                    showToast(getActivity().getString(R.string.delete_success));
                    employees.remove(preRemoveEmployee);
                    SystemConstant.employees = employees;
                    employeeAdapter.refresh(employees);
//                    inputUidDialog.dismiss();
                    break;
                case 1:
//                    YoYo.with(Techniques.Shake).playOn(inputUidDialog.findViewById(R.id.et_name));
                    showToast(getActivity().getString(R.string.count_is_not_exist));
                    break;
                case 3:
//                    YoYo.with(Techniques.Shake).playOn(inputUidDialog.findViewById(R.id.et_name));
                    showToast(getActivity().getString(R.string.count_had_been_added));
                    break;
                case 2:
                default:
                    showToast(getActivity().getString(R.string.add_failed));
                    break;
            }
        } else if (flag.equals(networkInteractUtil.GETEMPLOYEEASSIGNED)) {
            System.out.println("object=" + object.toString());
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        toolbar.setNavigationIcon(null);
    }
}
